package com.education.platform.common.util;

import com.education.platform.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 拷贝
 */
public class BeanUtil {

    private static final Logger logger = LoggerFactory.getLogger(BeanUtil.class);
    /**
     * 转换List
     *
     * @param list        源数据
     * @param targetClass 目标类类型
     * @return 目标类实例集合
     */
    public static <T, F> List<T> convert(List<F> list, Class<T> targetClass) {
        if(targetClass == null){
            throw new BusinessException("转换类型为空");
        }
        List<T> rs = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (F source : list) {
                try {
                    T target = targetClass.newInstance();
                    BeanUtils.copyProperties(source, target);
                    rs.add(target);
                } catch (Exception e) {
                    throw new BusinessException("类型转换异常");
                }
            }
        }
        return rs;
    }

    public static <S, R> R convert(S source, Class<R> targetClass) {
        try {
            if(source == null) {
                logger.error("source为空！");
                return null;
            }
            R target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
